import random
from datetime import datetime
from werkzeug.security import generate_password_hash
from flask import Blueprint, g, render_template, session, current_app, request, flash
from flask_mobility.decorators import mobilized

from .database import db
from .auth import login_required
from .crud import Users, Courses
from .router import to_route
from .schemas import user_schema, course_schema
from .models import User, Course
from .avatar import generate_avatar

bp = Blueprint('manage', __name__, url_prefix='/manage')

def status(online: bool):
    return 'off line' if online else 'online'

def formatDate(t: datetime):
    return t.strftime('%d/%m/%y')

@bp.before_app_request
def load_logged_in_user():
    user_id = session.get('user_id')
    if user_id is None:
        g.user = None
    else:
        g.user = Users.get_user(db.session, user_id)

@bp.route('/course', methods=('GET', 'POST'))
@login_required
def course():
    if request.method == 'POST':
        try:
            data = course_schema.load(request.form.to_dict())
            record = Course(name=data['name'], professor_id=data['professor_id'], online=True, school_year=data['school_year'], trimester=data['trimester'],
                duration=45, lessons=data['lessons'], progress=0, number_of_students=0, about=data['about'])
            Courses.save(db.session, record)
        except Exception as e:
            flash(str(e))

    courses = Courses.get_all_courses(db.session)
    professors = Users.get_all_professors(db.session)
    context = {
        'user': g.user,
        'status': status,
        'formatDate': formatDate,
        'courses': courses,
        'professors': professors,
        'school': current_app.config.get('SCHOOL_NAME')
    }
    return to_route('manage/course.html', **context)

@bp.route('/professor', methods=('GET', 'POST'))
@login_required
def professor():
    if request.method == 'POST':
        try:
            data = user_schema.load(request.form.to_dict())
            user = Users.get_user_by_email(db.session, data['email'])
            if not user is None:
                raise ValueError("Email already registered.")

            avatar = generate_avatar(data['email'])
            hashed_password = generate_password_hash(data['password'])
            record = User(email=data['email'], name=data['name'], role='professor',
                hashed_password=hashed_password, avatar=avatar,
                age=random.randrange(40, 70), gender='Male', address='6391 elgin St.celina Delaware 10299',
                post='Professor, School of Information', key_ompetency='Programming',
                skill_points=['Programming', 'Database design', 'Web development']
            )
            Users.save(db.session, record)
        except Exception as e:
            flash(str(e))

    professors = Users.get_all_professors(db.session)
    context = {
        'user': g.user,
        'professors': professors,
        'school': current_app.config.get('SCHOOL_NAME')
    }
    return to_route('manage/professor.html', **context)

@bp.route('/student', methods=('GET', 'POST'))
@login_required
def student():
    if request.method == 'POST':
        try:
            data = user_schema.load(request.form.to_dict())
            user = Users.get_user_by_email(db.session, data['email'])
            if not user is None:
                raise ValueError("Email already registered.")

            avatar = generate_avatar(data['email'])
            Users.create(db.session, data['email'], data['password'], 'student', data['name'], avatar)
        except Exception as e:
            flash(str(e))

    students = Users.get_all_students(db.session)
    context = {
        'user': g.user,
        'students': students,
        'school': current_app.config.get('SCHOOL_NAME')
    }
    return to_route('manage/student.html', **context)
